package $NAMESPACE.outapi.controller;

import com.ugeez.commons.account.dto.UserDto;
import com.ugeez.commons.account.persistence.entity.User;
import com.ugeez.commons.base.base.IdDTO;
import com.ugeez.commons.base.exception.BusinessException;
import com.ugeez.commons.base.utils.DtoUtil;
import com.ugeez.commons.core.enums.LoginDevice;
import com.ugeez.commons.security.annotation.Guest;
import com.ugeez.commons.security.vo.UserLoginResult;
import com.ugeez.commons.security.vo.UserSession;
import com.ugeez.commons.spring.utils.RequestUtils;
import $NAMESPACE.common.enums.ErrorCode;
import $NAMESPACE.domain.service.AppUserService;
import $NAMESPACE.outapi.dto.KeepAliveRes;
import $NAMESPACE.outapi.dto.LoginByUsernameReq;
import $NAMESPACE.outapi.dto.RegisterReq;
import $NAMESPACE.persistence.entity.AppUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;

@Slf4j
@RestController
@RequestMapping("/api/out/$PROJ/account")
public class AccountController {

    @Autowired
    private AppUserService appUserService;

    @Guest
    @PostMapping(value = "/register")
    public IdDTO<Long> register(@Valid @RequestBody RegisterReq req) {
        User user = appUserService.create(req.getUsername(), req.getPassword(), Arrays.asList("accountant", "auditor"));
        return new IdDTO<>(user.getId());
    }

    @Guest
    @PostMapping(value = "/login/username")
    public UserLoginResult loginByUsername(@Valid @RequestBody LoginByUsernameReq req) {
        UserLoginResult res = appUserService.login(req.getUsername(), req.getPassword(), LoginDevice.ANONYMOUS);
        if (res == null) {
            throw new BusinessException(ErrorCode.LOGIN_FAIL);
        }
        return res;
    }

    @PostMapping(value = "/keepAlive")
    public KeepAliveRes keepAlive() {
        UserSession userSession = appUserService.keepAlive((UserSession) RequestUtils.getUserContext());

        KeepAliveRes res = DtoUtil.convert(userSession, KeepAliveRes.class);

        AppUser user = appUserService.getSimpleInfoById(userSession.getUserId());
        res.setName(user.getName());
        res.setHead(user.getHead());
        res.setRoles(user.getRoles());

        return res;
    }

    @GetMapping(value = "/info")
    public UserDto info() {
        Long userId = RequestUtils.getUserId();
        User user = appUserService.getSimpleInfoById(userId);
        return DtoUtil.convert(user, UserDto.class);
    }

}
